package com.dai.train.member.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.dai.train.common.context.LoginMemberContext;
import com.dai.train.common.resp.PageResp;
import com.dai.train.common.util.SnowUtil;
import com.dai.train.member.domain.Passenger;
import com.dai.train.member.domain.PassengerExample;
import com.dai.train.member.mapper.PassengerMapper;
import com.dai.train.member.req.PassengerQueryReq;
import com.dai.train.member.req.PassengerSaveReq;
import com.dai.train.member.resp.PassengerQueryResp;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class PassengerService {

    Logger LOG = LoggerFactory.getLogger(PassengerService.class);

    @Autowired
    private PassengerMapper passengerMapper;


    public void save(PassengerSaveReq req){

        req.setId(SnowUtil.getSnowflakeNextId());
        req.setMemberId(LoginMemberContext.getId());
        req.setCreateTime(new Date());
        req.setUpdateTime(new Date());
        Passenger passenger = new Passenger();
        BeanUtil.copyProperties(req, passenger);
        passengerMapper.insert(passenger);

    }

    public PageResp<PassengerQueryResp> selectList(PassengerQueryReq req){

        PassengerExample passengerExample = new PassengerExample();
        if(ObjectUtil.isNotNull(req.getMemberId())){
            passengerExample.createCriteria().andMemberIdEqualTo(req.getMemberId());
        }
        PageHelper.startPage(req.getPage(), req.getSize()) ;
        List<Passenger> passengers = passengerMapper.selectByExample(passengerExample);
        PageInfo<Passenger> passengerPageInfo = new PageInfo<>(passengers);
        LOG.info("总行数：{}",passengerPageInfo.getSize());
        LOG.info("总页数：{}",passengerPageInfo.getPages());

        List<PassengerQueryResp> passengerQueryResps = BeanUtil.copyToList(passengers, PassengerQueryResp.class);
        PageResp<PassengerQueryResp> resp = new PageResp<>();
        resp.setList(passengerQueryResps);
        resp.setTotal(passengerPageInfo.getTotal());


        return resp;

    }

}
